package com.example.langchain4j.init;

import com.example.langchain4j.service.VectorizationService;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.DocumentParser;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import dev.langchain4j.data.document.parser.apache.pdfbox.ApachePdfBoxDocumentParser;
import jakarta.annotation.Resource;
import org.springframework.boot.CommandLineRunner;

import java.nio.file.FileSystems;
import java.nio.file.PathMatcher;
import java.util.List;

//@Component
public class PdfVectorizationInitializer implements CommandLineRunner {

    
    @Resource
    private VectorizationService vectorizationService;
    
    @Override
    public void run(String... args) throws Exception {

        //先清除全部向量
        vectorizationService.clearAll();
        System.out.println("开始初始化PDF文档向量化任务...");
        
        try {
            DocumentParser parser = new ApachePdfBoxDocumentParser();
            PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:*.pdf");
            List<Document> documents = FileSystemDocumentLoader.loadDocuments("backend/src/main/resources/knowledge", pathMatcher, parser);
            for (Document document : documents){
//                System.out.println(document.text());
                vectorizationService.vectorizeDocument(document);
            }
            
            System.out.println("PDF文档向量化初始化完成");
            
        } catch (Exception e) {
            System.err.println("PDF向量化初始化失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

}
